package cc.abanlee.framework.security.core.util;

import cc.abanlee.framework.security.core.LoginUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

/**
 * @author: create by
 * @version: v1.0
 * @description:
 * @date:2022/9/7
 */
public class SecurityFrameworkUtils {

    public static final String AUTHORIZATION_BEARER = "Bearer";

    /**
     * 从请求中，获得认证 Token
     *
     * @param request 请求
     * @param header 认证 Token 对应的 Header 名字
     * @return 认证 Token
     */
    public static String obtainAuthorization(HttpServletRequest request,String header){
        String authorization = request.getHeader(header);
        if(!StringUtils.hasText(authorization)){
            return null;
        }

        int index = authorization.indexOf(AUTHORIZATION_BEARER+" ");
        if(index==-1){
            return null;
        }
        return authorization.substring(index+7).trim();
    }

    /**
     * 设置当前用户
     * @param loginUser
     * @param request
     */
    public static void setLoginUser(LoginUser loginUser, HttpServletRequest request) {

        // 创建 Authentication，并设置到上下文
        Authentication authentication = buildAuthentication(loginUser, request);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    private static Authentication buildAuthentication(LoginUser loginUser, HttpServletRequest request) {
        // 创建 UsernamePasswordAuthenticationToken 对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                loginUser, null, Collections.emptyList());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        return authenticationToken;
    }
}
